<!--
 @description 搭配套餐配置列表
 @fileName index.vue
 @author zengqiongying
 @created 2024/08/16 11:08:11
-->
<template>
  <div class="qup-full-page">
    <template v-if="showEdit">
      <EditPage :page-show.sync="showEdit" :detail="activeRowData" @success="handlerEditSuccess" />
    </template>
    <div v-if="!(showProductConfig || showEdit )">
      <search-form
        ref="refSearch"
        :search-config="searchConfig"
        label-width="120"
        @clear="clearSearch"
        @search="handleSearch"
        @visible-change="resetTableHeight"
      />
      <table-box
        ref="refTable"
        table-size="small"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaws"
        :off-set="-10"
        show-index
        :show-selection="true"
        :selected-arry.sync="tableSelected"
        @selection-change="handleSelectionChange"
        @btnOperate="btnOperate"
        @row-click="handleRowClick"
      />
    </div>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { queryDetail, deleteCombine, updatState } from '@/api/productCombine/index'
import { getDictByPatchType } from '@/api/dataDict'
import EditPage from './Edit'
export default {
  name: 'ProductCombination',
  components: { EditPage },
  data() {
    const that = this
    return {
      showDetail: false,
      showProductConfig: false,
      showEdit: false,
      activeRowData: {},
      searchConfig: [
        { label: '搭配名称', prop: 'name', type: 'text', filter: false },
        { label: '商品名称', prop: 'skuName', type: 'text', filter: false },
        { label: '产品编码', prop: 'mdmCode', type: 'text', filter: false },
        { label: '产品名称', prop: 'mdmName', type: 'text', filter: false },
        { label: '商品类型', prop: 'isMain', type: 'select', filter: false,
          config: {
            selectData: [
              { label: '主商品', value: 1 },
              { label: '搭配商品', value: 0 }
            ]
          }
        },
        { label: '在产状态', prop: 'productState', type: 'select', filter: false,
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/PRODUCT_STATE?appCode=top-sad-channel&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        { label: '采购状态', prop: 'purchaseHandle', type: 'select', filter: false,
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/PURCHASE_HANDLE?appCode=top-sad-channel&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        { label: '关联方案名称', prop: 'schemeName', type: 'text', filter: false },
        { label: '状态', prop: 'enabled', type: 'select', value: 1, filter: false,
          config: {
            selectData: [
              { label: '启用', value: 1 },
              { label: '停用', value: 0 }
            ]
          }
        },
        { label: '清单配置', prop: 'productConfig', type: 'select', value: '', filter: false,
          config: {
            selectData: [
              { label: '已配置', value: 1 },
              { label: '未配置', value: 0 }
            ]
          }
        },
        { label: '效果图配置', prop: 'renderingConfig', type: 'select', value: '', filter: false,
          config: {
            selectData: [
              { label: '已配置', value: 1 },
              { label: '未配置', value: 0 }
            ]
          }
        },
        { label: '显示方式', prop: 'showType', type: 'select', value: '', filter: false,
          config: {
            selectData: [
              { label: 'SPU', value: 'SPU' },
              { label: 'SKU', value: 'SKU' }
            ]
          }
        },
        { label: '创建时间', prop: 'createTime', type: 'date', value: '', dateType: 'daterange', filter: false },
        { label: '创建人', prop: 'createBy', type: 'text', filter: false },
        { label: '修改时间', prop: 'lastUpdateTime', type: 'date', value: '', dateType: 'daterange', filter: false },
        { label: '修改人', prop: 'lastUpdateBy', type: 'text', filter: false }
      ],
      otherFilters: [],
      otherRaws: {},
      tableSelected: [], // 选择列
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/productCombination/voPage`,
        tabIndex: 0,
        hideSearchBar: true,
        pageSize: 20,
        sort: 'createTime',
        order: 'desc',
        apiHeader: {
          // 'Permission-PerCode': 'combin_package',
          // 'Permission-App': 'top-sad-channel'
        },
        // 页面权限码：combin_package
        setting: [
          /* {
            prop: 'code',
            label: '套餐编码',
            minWidth: 150,
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleDetailPage
          }, */
          {
            prop: 'name',
            label: '搭配名称',
            minWidth: 200
          },
          {
            prop: 'skuName',
            label: '商品名称',
            minWidth: 200,
            render: (h, row) => that.renderProdTdContent(h, row, 'skuName')
          },
          {
            prop: 'mdmCode',
            label: '产品编码',
            width: 120,
            render: (h, row) => that.renderProdTdContent(h, row, 'mdmCode')
          },
          {
            prop: 'mdmName',
            label: '产品名称',
            minWidth: 150,
            render: (h, row) => that.renderProdTdContent(h, row, 'mdmName')
          },
          {
            prop: 'isMain',
            label: '商品类型',
            width: 100,
            render: (h, row) => that.renderProdTdContent(h, row, 'isMain', (val) => {
              return [1, '1'].includes(val) ? '主商品' : '搭配商品'
            })
          },
          {
            prop: 'productState',
            label: '在产状态',
            width: 100,
            render: (h, row) => that.renderProdTdContent(h, row, 'productState', (val) => {
              return that.getDictName('PRODUCT_STATE', val)
            })
          },
          {
            prop: 'purchaseHandle',
            label: '采购状态',
            width: 100,
            render: (h, row) => that.renderProdTdContent(h, row, 'purchaseHandle', (val) => {
              return that.getDictName('PURCHASE_HANDLE', val)
            })
          },
          {
            prop: 'schemeName',
            label: '关联方案名称',
            minWidth: 150,
            formatData: ({ productCombinationSchemeDTOs }) => {
              const list = productCombinationSchemeDTOs || []
              return list.length > 0 ? list[0].schemeName : ''
            }
          },
          {
            prop: 'enabled',
            label: '启用状态',
            width: 100,
            formatData: ({ enabled }) => {
              return [1, '1'].includes(enabled) ? '启用' : '停用'
            }
          },
          {
            prop: 'productConfig',
            label: '清单配置',
            width: 100,
            formatData: ({ productCombinationDetailDTOs }) => {
              return productCombinationDetailDTOs && productCombinationDetailDTOs.length > 0 ? '已配置' : '未配置'
            }
          },
          {
            prop: 'renderingConfig',
            label: '效果图配置',
            width: 120,
            formatData: ({ productCombinationRenderingDTOs }) => {
              return productCombinationRenderingDTOs && productCombinationRenderingDTOs.length > 0 ? '已配置' : '未配置'
            }
          },
          {
            prop: 'showType',
            label: '显示方式',
            width: 100
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 150
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 150,
            formatData: ({ createTime }) => {
              return parseTime(createTime, '{y}-{m}-{d} {h}:{i}:{s}')
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            minWidth: 150
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            width: 150,
            formatData: ({ lastUpdateTime }) => {
              return parseTime(lastUpdateTime, '{y}-{m}-{d} {h}:{i}:{s}')
            }
          }
        ],
        btnList: !this.isProduction ? [
          {
            buttonName: '新增',
            optCode: 'add',
            outerFlag: true
          },
          {
            buttonName: '编辑',
            optCode: 'edit',
            outerFlag: true
          },
          {
            buttonName: '删除',
            optCode: 'del',
            outerFlag: true
          },
          {
            buttonName: '启用',
            optCode: 'enable',
            outerFlag: true
          },
          {
            buttonName: '停用',
            optCode: 'disable',
            outerFlag: true
          }
        ] : null
      },
      dictData: {}
    }
  },

  computed: {},

  async created() {
    this.dictData = await getDictByPatchType(['PRODUCT_STATE', 'PURCHASE_HANDLE'])
  },
  activated() {},

  mounted() {},

  methods: {
    getDictName(typeCode, dictCode) {
      const tmps = this.dictData[typeCode] || []
      const d = tmps.find(v => v.dictCode === dictCode)
      return d && d.dictName
    },
    renderProdTdContent(h, row, fileName, formatFun) {
      const tdRows = []
      const proDTO = row.productCombinationDetailDTOs || []
      proDTO.forEach(v => {
        let val = [null, undefined].includes(v[fileName]) ? '' : v[fileName]
        if (formatFun instanceof Function) {
          val = formatFun(val)
        }
        tdRows.push(h('div', { class: 'td-row' }, val))
      })
      return h('div', tdRows)
    },
    resetTableHeight() {
      this.$refs.refTable.refreshTableHeight()
    },
    handleRowClick({ row }) {
      this.$refs.refTable.clearSelection()
      this.$nextTick(() => {
        this.$refs.refTable.toggleRowSelection(row, true)
        this.activeRowData = row || {}
      })
    },
    clearSearch() {

    },
    // 搜索
    handleSearch(params) {
      const { filtersRaw, paramsRaw } = params
      if (paramsRaw.createTime) {
        const vals = paramsRaw.createTime
        paramsRaw.createTimeBegin = vals[0]
        paramsRaw.createTimeEnd = vals[1]
        delete paramsRaw.createTime
      }

      if (paramsRaw.lastUpdateTime) {
        const vals = paramsRaw.lastUpdateTime
        paramsRaw.lastUpdateTimeBegin = vals[0]
        paramsRaw.lastUpdateTimeEnd = vals[1]
        delete paramsRaw.lastUpdateTime
      }

      this.otherFilters = filtersRaw || []
      this.otherRaws = paramsRaw
      this.refreshTable(true)
    },
    // 刷新主表
    refreshTable(isInit) {
      this.$nextTick(() => {
        this.$refs.refTable && this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
        this.tableSelected = []
      })
    },
    handleSelectionChange(rows) {
      this.tableSelected = rows
    },
    btnOperate(code) {
      switch (code) {
        case 'add' :
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'enable':
          if (!this.singleJudge(this.tableSelected, '启用', true)) {
            return
          }
          this.handleChangetatus(1)
          break
        case 'disable':
          if (!this.singleJudge(this.tableSelected, '停用', true)) {
            return
          }
          this.handleChangetatus(0)
          break
        case 'del' :
          if (!this.singleJudge(this.tableSelected, '删除', true)) {
            return
          }
          if ([1, '1'].includes(this.tableSelected[0].enabled)) {
            this.$message.warning('启用状态的搭配不能操作删除')
            return
          }
          this.handleDelete(this.tableSelected[0])
          break
        default:
          break
      }
    },
    handleEdit(row) {
      this.showDetail = false
      this.showProductConfig = false
      this.activeRowData = row && row.id ? row : {}
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    handleDetailPage(row) {
      queryDetail(row.id).then(res => {
        if (res.data && res.data.id) {
          this.showEdit = false
          this.showProductConfig = false
          this.activeRowData = res.data || {}
          this.$nextTick(() => {
            this.showDetail = true
          })
        }
      })
    },
    handleDelete() {
      this.$confirm('确定要删除当前所选搭配吗？一旦删除，将无法恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = this.tableSelected[0].id
        deleteCombine(id).then(res => {
          if (res.success === 1) {
            this.$message.success('操作成功')
            this.refreshTable()
          }
        })
      })
    },
    handleChangetatus(status) {
      let confirmMsg = `此操作将当前搭配状态设置为【${status ? '启用' : '停用'}】,是否继续？`
      if (status) {
        confirmMsg = `请确认清单及效果图都已配置完成，启用后将进行显示.`
      }
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.tableSelected.map(v => v.id)
        updatState({ ids, status }).then(res => {
          if (res.success === 1) {
            this.$message.success('操作成功')
            this.refreshTable()
          }
        })
      })
    },
    handlerEditSuccess(d) {
      this.refreshTable(!!(d.data && d.isNewCreate))
      this.activeRowData = d.data || {}
    }
  }
}

</script>
<style lang='scss' scoped>
/deep/.td-row{
  width: 100%;
  height: 22px;
  line-height: 22px;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
